package pers.cocoadel.cloud.upload.controller;

import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;

@Controller
public class FileUploadController
{

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ResponseBody
    public String handleFileUpload(@RequestParam(value = "file") MultipartFile file) throws IOException
    {
        String fileName = file.getOriginalFilename();
        if (!StringUtils.isEmpty(fileName))
        {
            InputStream is = file.getInputStream();
            File fileToSave = new File(fileName);
            FileOutputStream fos = new FileOutputStream(fileToSave);
            byte[] buffer = new byte[1024];
            int len;
            while ((len = is.read(buffer)) > 0)
            {
                fos.write(buffer, 0, len);
            }
            is.close();
            fos.flush();
            fos.close();
            return fileToSave.getAbsolutePath();
        }
        return "/";
    }
}
